package com.example.demo.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.domain.Article;
import com.example.demo.domain.ArticleImage;
import com.example.demo.domain.Category;
import com.example.demo.domain.Tag;
import com.example.demo.domain.User;
import com.example.demo.domain.dto.ArticleDTO;
import com.example.demo.service.ArticleImageService;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoryService;
import com.example.demo.service.TagService;
import com.example.demo.service.storage.StorageService;

@Controller
public class ArticleController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	ArticleService articleService;
	@Autowired
	StorageService storageService;
	@Autowired
	ArticleImageService articleImageService;
	@Autowired
	CategoryService categoryService;
	@Autowired
	TagService tagService;

	@RequestMapping("/articles")
	public String getArticle(Model model) {
		List<ArticleDTO> articleDTOs = new ArrayList<ArticleDTO>();
		articleDTOs = articleService.loadAllArticleDTO();
		model.addAttribute("articleDTOs", articleDTOs);
		return "articles";
	}

	@RequestMapping("article/{aid}")
	public String articleDetail(Model model, @PathVariable("aid") Long aid) {
		ArticleDTO articleDTO = new ArticleDTO();
		articleDTO = articleService.loadArticleDTOByAid(aid);
		if(articleDTO!=null) {
			model.addAttribute("articleDTO", articleDTO);
		}
		return "article-details";
	}

	@RequestMapping("article/tag/{tid}")
	public String articlesOfSameTag(Model model, @PathVariable Integer tid) {
		logger.info("----ArticleController: articlesOfSameTag()");
		logger.info("tid: "+String.valueOf(tid));
		List<ArticleDTO> articleDTOs = new ArrayList<ArticleDTO>();
		articleDTOs = articleService.loadAllArticleDTOsByTag(tid);
		model.addAttribute("articleDTOs", articleDTOs);

		return "articles";
	}

	/**
	 * 用于返回json测试
	 * 
	 **/
	@RequestMapping("/article2")
	@ResponseBody
	public List<ArticleDTO> getArticle2(Model model) {
//		User u = new User();
//		u.setUid(1000000073);
//		List<ArticleDTO> articleDTOs = new ArrayList<ArticleDTO>();
//		articleDTOs = articleService.loadAllArticleDTOByUser(u);
//		model.addAttribute("articleDTOs", articleDTOs);
//		return articleDTOs;

		return articleService.loadAllArticleDTO();
	}

	@RequestMapping("/add")
	public String toAddArticle(HttpSession session, Model model) {

		if (session.getAttribute("user") == null) {
			return "login";
		}
		// 加载文章类别、文章标签放入model中
		model.addAttribute("categories", categoryService.getCategories());
		model.addAttribute("tags", tagService.getTags());
		List<Category> categories = categoryService.getCategories();
		List<Tag> tags = tagService.getTags();
		for (Category cg : categories) {
			logger.info(cg.toString());
		}
		for (Tag t : tags) {
			logger.info(t.toString());
		}
		return "article-add";
	}

	/**
	 * ModelAttribute里的值以及RequestParam里的变量可以不写
	 * 
	 * @param article
	 * @param files
	 * @return
	 */
	@RequestMapping("/article/add")
	public String addArticle(@ModelAttribute Article article, @RequestParam MultipartFile[] files, HttpSession session,
			@RequestParam Integer[] tags) {

		logger.info("----addArticle(): ");
		User u = (User) session.getAttribute("user");
		logger.info(Arrays.toString(tags));
//		if(u==null) {
//			return "login";
//		}
		article.setUid(u.getUid());

		// 此处Mybatis会自动绑定article主键Aid @see
		// /demo/src/main/resources/mappers/ArticleMapper.xml
		articleService.addArticle(article);

		// 遍历上传的图片，绑定
		// 判断是否有图片（FileInput存在问题，改用后端判断）
		System.out.println(files.length);
		// 非空，遍历，添加articleImage
		for (MultipartFile file : files) {
			if (file.isEmpty()) {
				// 为空，添加默认的图片名
				// 原因：没有图片时，files.length仍然大于1
				ArticleImage articleImage = new ArticleImage();
				articleImage.setAid(article.getAid());
				articleImage.setName("logo.png");
				articleImageService.addImageOfArticle(articleImage);
				break;
			} 
			else {
				ArticleImage articleImage = new ArticleImage();
				articleImage.setAid(article.getAid());
				articleImage.setName(storageService.store(file));
				logger.info("----articleImage: " + articleImage.toString());
				articleImageService.addImageOfArticle(articleImage);
			}
		}
		// 绑定标签
		for (Integer tagId : tags) {
			tagService.addTagOfArticle(article.getAid(), tagId);
		}

		return "redirect:/articles";
	}
}
